package com.diy.sigmund.diycommon.entity.enumerate;

import com.diy.sigmund.diycommon.entity.base.exception.DiyRuntimeException;
import com.diy.sigmund.diycommon.entity.CustomUser;
import com.diy.sigmund.diycommon.entity.constant.HeaderConstant;
import com.diy.sigmund.diycommon.entity.constant.UserConstant;
import com.diy.sigmund.diycommon.spring.ContextHolder;
import com.diy.sigmund.diycommon.entity.bo.RuleProcessParam;
import com.diy.sigmund.diycommon.middleware.cache.redis.RedisService;
import com.diy.sigmund.diycommon.util.time.DateUtil;
import java.util.Date;
import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author ylm-sigmund
 * @since 2021/8/30 11:10
 */
public enum WebInterceptorRuleEnum {

    /** 网关外部请求 */
    TOKEN(HeaderConstant.TOKEN) {
        @Override
        public boolean process(RuleProcessParam ruleProcessParam) {
            log.info("进入网关外部请求");
            RedisService redisService = ruleProcessParam.getRedisService();
            // 不用判断key是否存在，因为经过网关已经刷新了失效时间
            String key = UserConstant.USER_ACCESS_TOKEN + ruleProcessParam.getToken();

            // 从缓存中获取用户信息
            CustomUser customUser = (CustomUser) redisService.get(key);
            if (Objects.isNull(customUser)) {
                CustomUser customUser1 = new CustomUser();
                customUser1.setUserId(DateUtil.parseDateToStr(new Date(),DateUtil.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
                ContextHolder.getInstance().setCustomUser(customUser1);
                return true;
                // log.info("请求用户获取失败");
                // throw new DiyRuntimeException(ResponseEnum.FAILED_TO_REQUEST_USER_ACQUISITION);
            }
            // 将用户信息设置到上下文
            ContextHolder.getInstance().setCustomUser(customUser);
            return true;
        }
    },
    /** feign内部调用请求 */
    INNER_TOKEN(HeaderConstant.INNER_TOKEN) {
        @Override
        public boolean process(RuleProcessParam ruleProcessParam) {
            // 判断feign调用时传入的token值是否匹配，不匹配则抛出异常
            if (!Objects.equals(HeaderConstant.INNER_TOKEN_VALUE, ruleProcessParam.getInnerToken())) {
                log.info("当前为非法feign内部调用请求");
                throw new DiyRuntimeException(ResponseEnum.ILLEGAL_FEIGN_INTERNAL_CALL);
            }
            log.info("进入feign内部调用");
            return true;
        }
    },
    /** 无效请求 */
    OTHER(HeaderConstant.OTHER) {
        @Override
        public boolean process(RuleProcessParam ruleProcessParam) {
            log.info("未能获取到token信息，请检查请求头信息或接口注解信息");
            throw new DiyRuntimeException(ResponseEnum.FAILED_TO_GET_TOKEN);
        }
    };

    String name;
    private static final Logger log = LoggerFactory.getLogger(WebInterceptorRuleEnum.class);

    public abstract boolean process(RuleProcessParam ruleProcessParam);

    WebInterceptorRuleEnum(String name) {
        this.name = name;
    }

}
